package connect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import com.example.administrator.bluetoothdemo01.util.Constant;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by Lzz on 8/5/2017.
 *
 *
 *  服务器端的连接
 *
 */

public class AcceptThread extends Thread {

    private final static String NAME = "BlueToothClass";
    private final static UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUII); // 一致性

    private final BluetoothServerSocket mBluetoothServerSocket;
    private final Handler mHandler;
    private final BluetoothAdapter mBluetoothAdapter;
    private ConnectedThread mConnectedThread;

    public AcceptThread(Handler handler, BluetoothAdapter bluetoothAdapter) {
        mHandler = handler;
        mBluetoothAdapter = bluetoothAdapter;
        BluetoothServerSocket tmp = null;
        try {
            // 获得一个 服务器 socket
            tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mBluetoothServerSocket = tmp;
    }




    @Override
    public void run() {
        super.run();
        BluetoothSocket socket = null;
        while(true) {
            try {
                mHandler.sendEmptyMessage(Constant.MSG_START_LISTENING);
                socket = mBluetoothServerSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
                mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, e));
                break;
            }

            if (socket!=null){
                managConnectedThread(socket);
                try {
                    mBluetoothServerSocket.close();
                    mHandler.sendEmptyMessage(Constant.MSG_END_LISTENING);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    private void managConnectedThread(BluetoothSocket socket) {
        // 只支持同时处理一个连接
        if (mConnectedThread !=null) {
            mConnectedThread.cancel();
        }
        mHandler.sendEmptyMessage(Constant.MSG_GOT_A_CLINET); // 有一个客户端申请
        mConnectedThread = new ConnectedThread(socket,mHandler);
        mConnectedThread.start();
    }



    //写操作
    public void sendData(byte[] bytes) {
        if (mConnectedThread != null) {
            mConnectedThread.write(bytes);
        }
    }



    public void cancel(){
        if (mBluetoothServerSocket!=null) {
            try {
                mBluetoothServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
